import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import '../models/ReadingParams.dart';
import '../models/catalogue.dart';
import 'theme_notifier.dart';
import 'package:my_ebook_app/models/book.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:path/path.dart' as path;

final List<String> categories = ['Art', 'Business', 'Computers', 'Fiction', 'History', 'Science'];

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _selectedIndex=0;
  bool _showSearchBar = false;
  bool _isSettingsMenuOpen = false;
  String _defaultBook = '杀死一只知更鸟';
  late ReadingBook readingBook;
  late Catalogue bookCatalogue;
  final Map<String, double> bookCatalogues= {};
  final TextEditingController _searchController = TextEditingController();

  List<HomeBook> recommendedBooks = [];
  List<HomeBook> popularBooks = [];
  List<HomeBook> newBooks = [];
  bool _isLoading = true;
  String _errorMessage = '';

  @override
  void initState() {
    super.initState();
    _fetchBooks();
  }

  // 从后端获取书籍数据
  Future<void> _fetchBooks() async {
    try {
      final response = await http.get(Uri.parse('http://10.0.2.2:8080/home'));

      if (response.statusCode == 200) {
        final List<dynamic> data = json.decode(response.body);

        for( int i=0 ; i< data.length ; i++) {
          if( i < 3){
            recommendedBooks.add(HomeBook(
              title: data[i]['bookName'],
              author: data[i]['bookAuthor'],
              image: 'lib/common/images/${path.basename(data[i]['bookCover'])}',
              rating: (data[i]['bookRatings'] as num).toDouble(),
            ));
          }
          else if( i>=3 && i < 6){
            popularBooks.add(HomeBook(
              title: data[i]['bookName'],
              author: data[i]['bookAuthor'],
              image: 'lib/common/images/${path.basename(data[i]['bookCover'])}',
              rating: (data[i]['bookRatings'] as num).toDouble(),
            ));
          }
          else{
            newBooks.add(HomeBook(
              title: data[i]['bookName'],
              author: data[i]['bookAuthor'],
              image: 'lib/common/images/${path.basename(data[i]['bookCover'])}',
              rating: (data[i]['bookRatings'] as num).toDouble(),
            ));
          }

        }
        setState(() {
          _isLoading = false;
          _errorMessage = '';
        });
      } else {
        setState(() {
          _isLoading = false;
          _errorMessage = '加载失败: ${response.statusCode}';
        });
      }
    } catch (e) {
      setState(() {
        _isLoading = false;
        _errorMessage = '错误: $e';
      });
    }
  }

  Future<void> _fetchReadingBook(String bookName) async {
    try {
      final response = await http.get(Uri.parse('http://10.0.2.2:8080/reading/info?bookName=${bookName}'));

      if (response.statusCode == 200) {
        final dynamic data = json.decode(response.body);
          readingBook = ReadingBook(
          title: data['bookName'],
          totalChar: data['totalChar'],
          epubPath: data['bookAddress'],
          progress: (data['progress'] as num).toDouble(),
          localPath: data['localBookAddress'],
        );

        setState(() {
          _isLoading = false;
        });
      } else {
        setState(() {
          _isLoading = false;
          _errorMessage = '加载失败: ${response.statusCode}';
        });
      }
    } catch (e) {
      print('错误: $e');
      setState(() {
        _isLoading = false;
        _errorMessage = '错误: $e';
      });
    }
  }

  Future<void> _fetchBookCatalogue(String bookName) async {
    try {
      final response = await http.get(Uri.parse('http://10.0.2.2:8080/reading/catalogue?bookName=${bookName}'));

      if (response.statusCode == 200) {
        final dynamic data = json.decode(response.body);
        for( int i=0 ; i< data.length ; i++){
          bookCatalogues[data[i]['chapterName']] = (data[i]['chapterPosition'] as num).toDouble();
        }
        bookCatalogue = Catalogue(
          bookName: bookName,
          bookCatalogues: bookCatalogues,
        );

        setState(() {
          _isLoading = false;
        });
      } else {
        setState(() {
          _isLoading = false;
          _errorMessage = '加载失败: ${response.statusCode}';
        });
      }
    } catch (e) {
      print('错误: $e');
      setState(() {
        _isLoading = false;
        _errorMessage = '错误: $e';
      });
    }
  }

  void _handleReadingBook(String bookName) async {
    await _fetchReadingBook(bookName);
    await _fetchBookCatalogue(bookName);
    await context.push('/reading', extra: ReadingParams(readingBook, bookCatalogue));
  }
  void _toggleSettingsMenu() {
    setState(() {
      _isSettingsMenuOpen = !_isSettingsMenuOpen;
    });
  }

  void _closeSettingsMenu() {
    if (_isSettingsMenuOpen) {
      setState(() {
        _isSettingsMenuOpen = false;
      });
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final currentRoute = GoRouterState.of(context).fullPath;
    if (currentRoute == '/home') {
      setState(() => _selectedIndex = 0);
    }
  }

  @override
  Widget build(BuildContext context) {
    final isDarkMode = Theme.of(context).brightness == Brightness.dark;
    // 显示加载状态
    if (_isLoading) {
      return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(),
              SizedBox(height: 20),
              Text('加载书籍数据中...'),
            ],
          ),
        ),
      );
    }
    // 显示错误信息
    if (_errorMessage.isNotEmpty) {
      return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(_errorMessage),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: _fetchBooks,
                child: Text('重试'),
              ),
            ],
          ),
        ),
      );
    }
    return GestureDetector(
      onTap: _closeSettingsMenu,
      child: Scaffold(
        body: Stack(
          children: [
            // 主内容区域
            Column(
              children: [
                // 顶部栏（仅在搜索框不显示时出现）
                if (!_showSearchBar)
                // 顶部栏
                  Padding(
                    padding: const EdgeInsets.only(
                      top: 18,
                      left: 20,
                      right: 10,
                      bottom: 2,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        const Text('书籍类别',
                            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                        Row(
                          children: [
                            // 搜索
                            IconButton(
                              icon: const Icon(Icons.search_outlined, size: 26),
                              onPressed: () {
                                setState(() {
                                  _showSearchBar = true;
                                  _closeSettingsMenu();
                                });
                              },
                            ),
                            IconButton(
                              icon: Icon(
                                Icons.settings_outlined,
                                size: 26,
                                color: _isSettingsMenuOpen ? Colors.grey[300] : null, // 菜单打开时图标变淡
                              ),
                              onPressed: _toggleSettingsMenu,
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                // 类别导航栏
                if (!_showSearchBar)
                  Container(
                    height: 41,
                    color: Colors.black,
                    child: ListView.builder(
                      scrollDirection: Axis.horizontal,
                      itemCount: categories.length,
                      itemBuilder: (context, index) {
                        return Row(
                          children: [
                            Padding(
                              padding: const EdgeInsets.symmetric(horizontal: 24.0),
                              child: Center(
                                child: Text(
                                  categories[index],
                                  style: TextStyle(
                                    color: isDarkMode?Colors.grey:Colors.white,
                                    fontSize: 15,
                                  ),
                                ),
                              ),
                            ),
                            if (index < categories.length - 1)
                              Container(
                                height: 20,
                                width: 1,
                                color: Colors.grey,
                              ),
                          ],
                        );
                      },
                    ),
                  ),
                SizedBox(height: 5),
                // 分隔线
                Container(
                  height: 1,
                  color: Colors.grey,
                  margin: EdgeInsets.only(top: 12),
                ),
                // 内容区域
                Expanded(
                  child: ListView(
                    children: [
                      _buildSectionTitle('为您推荐'),
                      SizedBox(
                        height: 240,
                        child: ListView.builder(
                          scrollDirection: Axis.horizontal,
                          itemCount: recommendedBooks.length,
                          itemBuilder: (context, index) {
                            return _buildBookCard(recommendedBooks[index],isDarkMode);
                          },
                        ),
                      ),
                      SizedBox(height: 10),
                      _buildSectionTitle('最受欢迎'),
                      Padding(
                        padding: EdgeInsets.only(left: 6),
                        child: SizedBox(
                          height: 72,
                          child: ListView.builder(
                            scrollDirection: Axis.horizontal,
                            itemCount: popularBooks.length,
                            itemBuilder: (context, index) {
                              return _buildPopularBookCard(popularBooks[index],isDarkMode);
                            },
                          ),
                        ),
                      ),
                      // 分隔线
                      Container(
                        height: 1,
                        color: Colors.grey,
                        margin: EdgeInsets.only(top: 20),
                      ),
                      // 新的书籍
                      Padding(
                        padding: EdgeInsets.all(14.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text('新的书籍', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
                            Text('更多...',
                              style: TextStyle(
                                  fontSize: 20, fontWeight: FontWeight.bold,
                                  color: Colors.grey),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 200,
                        child: ListView.builder(
                          scrollDirection: Axis.horizontal,
                          itemCount: newBooks.length,
                          itemBuilder: (context, index) {
                            return _buildBookCard(newBooks[index],isDarkMode);
                          },
                        ),
                      ),
                      SizedBox(height: 60),
                    ],
                  ),
                ),
              ],
            ),


            if (_isSettingsMenuOpen && !_showSearchBar) // 确保搜索框显示时不显示设置菜单
            // 设置菜单弹窗
              Positioned(top: 50, right: 16,
                child: Material(
                  elevation: 4,
                  borderRadius: BorderRadius.circular(8),
                  child: Container(width: 180, padding: EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8),
                      color: isDarkMode ? Color(0xFF32383E) : Color(0x80F6EEFA),
                    ),
                    child: Column(crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 深色模式开关
                        Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: [
                            Text("深色模式",
                                style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold
                                )
                            ),
                            Transform.scale(
                              scale: 0.8,
                              child:  Consumer<ThemeNotifier>(
                                builder: (context, themeNotifier, child) {
                                  return Transform.scale(
                                    scale: 0.8,
                                    child: Switch(
                                      value: themeNotifier.themeMode == ThemeMode.dark,
                                      onChanged: (value) {
                                        themeNotifier.setThemeMode(
                                            value ? ThemeMode.dark : ThemeMode.light
                                        );
                                      },
                                      activeColor: Colors.blue,
                                    ),
                                  );
                                },
                              )
                            )
                          ],
                        ),
                        Divider(height: 18, thickness: 1),
                        // 退出登录按钮
                        InkWell(onTap: () {
                            _closeSettingsMenu();
                            context.push('/welcome');
                          },
                          child: Container(
                              child: Padding(
                                padding: const EdgeInsets.symmetric(horizontal: 8.0),
                                child: Row(
                                  children: [
                                    Text("退出登录", style: TextStyle(fontSize: 16, color: Colors.red)),
                                    SizedBox(width: 30),
                                    Icon(Icons.exit_to_app, size: 26, color: Colors.red),
                                  ],
                                ),
                              )
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),

            if (!_showSearchBar)
              Positioned(bottom: 0, left: 0, right: 0,
                child: Container(decoration: BoxDecoration(
                    border: Border(top: BorderSide(color: Colors.grey.shade300)),
                    color: isDarkMode ? Color(0x8032383E) : Color(0x80F6EEFA)
                  ),
                  child: BottomNavigationBar(currentIndex: _selectedIndex,
                    type: BottomNavigationBarType.fixed,
                    unselectedLabelStyle: const TextStyle(fontSize: 10),
                    selectedLabelStyle: const TextStyle(fontSize: 12),
                    items: const [
                      BottomNavigationBarItem(
                        icon: Icon(Icons.home_outlined),
                        label: "首页",
                      ),
                      BottomNavigationBarItem(
                        icon: Icon(Icons.menu_book_outlined),
                        label: "书架",
                      ),
                      BottomNavigationBarItem(
                        icon: Icon(Icons.book_outlined),
                        label: "书",
                      ),
                    ],
                    onTap: (int index) {
                      setState(() {
                        _selectedIndex = index;
                      });
                      switch(index){
                        case 0:
                          context.push('/home');
                          break;
                        case 1:
                          context.push('/bookshelf');
                          break;
                        case 2:
                          _handleReadingBook(_defaultBook);
                          break;
                      }},
                  ),
                ),
              ),
            // 搜索框和遮罩层
            if (_showSearchBar)
              Positioned.fill(
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      _showSearchBar = false;
                      _searchController.clear();
                      _closeSettingsMenu(); // 关闭搜索时也关闭设置菜单
                    });
                  },
                  child: Container(
                    color: Colors.black54, // 半透明黑色遮罩
                  ),
                ),
              ),
            // 搜索框（固定在顶部）
            if (_showSearchBar)
              Positioned(
                top: 15,
                left: 0,
                right: 0,
                child: Container(
                  height: 67,
                  padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(10),
                      bottomRight: Radius.circular(10),
                    ),
                    color: isDarkMode?Color(0xFF32383E):Color.fromRGBO(246, 238, 250, 1.0),
                  ),
                  child: Row(
                    children: [
                      IconButton(
                        icon: const Icon(Icons.arrow_back),
                        onPressed: () {
                          setState(() {
                            _showSearchBar = false;
                            _searchController.clear();
                            _closeSettingsMenu(); // 关闭搜索时也关闭设置菜单
                          });
                        },
                      ),
                      Expanded(
                        child: TextField(
                          controller: _searchController,
                          autofocus: true,
                          decoration: const InputDecoration(
                            hintText: '搜索书籍...',
                            border: InputBorder.none,
                          ),
                        ),
                      ),
                      IconButton(
                        icon: const Icon(Icons.search),
                        onPressed: () {
                          if (_searchController.text.isNotEmpty) {
                            print('搜索内容: ${_searchController.text}');
                            // 实际搜索逻辑
                          }
                        },
                      ),
                    ],
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: EdgeInsets.only(left: 20,bottom: 20),
      child: Text(
        title,
        style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
      ),
    );
  }

  Widget _buildBookCard(HomeBook book,bool isDarkMode) {
    return GestureDetector(
      onTap: () {
        context.push('/detail', extra: book.title);
      },
      child:  Container(
        width: 160,
        margin: const EdgeInsets.symmetric(horizontal: 8.0),
        padding: EdgeInsets.only(left: 8),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(8.0),
          child: ColorFiltered(
            colorFilter: isDarkMode
                ? ColorFilter.mode(
              Colors.black26,
              BlendMode.darken,
            )
                : ColorFilter.mode(Colors.transparent, BlendMode.srcATop),
            child: Image.asset(
              book.image,
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildPopularBookCard(HomeBook book,bool isDarkMode) {
    return  GestureDetector(
      onTap: () {
        context.push('/detail', extra: book.title);
      },
      child: Container(
        width: 200,
        decoration: BoxDecoration(
          color: Colors.black,
          borderRadius: BorderRadius.circular(8.0),
        ),
        margin: const EdgeInsets.symmetric(horizontal: 10.0),

        child: Row(
          children: [
            Padding(
              padding: EdgeInsets.only(top: 1,left: 8,bottom: 1),
              // 封面
              child: Container(
                width: 45,
                height:62,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(2.0),
                  image: DecorationImage(
                    image: AssetImage(book.image),
                    fit: BoxFit.cover,
                    colorFilter: isDarkMode?
                    ColorFilter.mode(
                      Color(0x80000000),
                      BlendMode.darken,
                    )
                        :null,
                  ),
                ),
              ),
            ),
            const SizedBox(width: 16.0),
            // 题目、作者、评分
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    book.title,
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        color: isDarkMode?Colors.grey:Colors.white
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 2),
                  Text(
                    book.author,
                    style: const TextStyle(fontSize: 12, color: Colors.grey),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 2),
                  Row(
                    children: List.generate(5, (index) {
                      return Icon(
                        Icons.star,
                        color: index < book.rating!.round() ? Colors.amber : Colors.grey,
                        size: 16,
                      );
                    }),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
